package cn.gov.pbc.gd.credit.user.service.dictionary.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.liu.jbase.ResultVo;
import com.liu.jbase.service.impl.BaseServiceImpl;
import com.liu.tools.LogUtil;
import com.liu.tools.StrUtil;

import cn.gov.pbc.gd.credit.api.dictionary.IDictionaryApi;
import cn.gov.pbc.gd.credit.common.constant.CodeConstant;
import cn.gov.pbc.gd.credit.common.constant.CommonConstant;
import cn.gov.pbc.gd.credit.common.constant.ConfConstant;
import cn.gov.pbc.gd.credit.common.service.redis.IRedisService;
import cn.gov.pbc.gd.credit.user.service.dictionary.IDictionaryService;
import cn.gov.pbc.gd.credit.vo.dictionary.DictionaryVo;
import cn.gov.pbc.gd.credit.vo.dictionary.ResDictionaryVo;

@Service
public class DictionaryServiceImpl extends BaseServiceImpl<ResDictionaryVo, DictionaryVo, IDictionaryApi> implements IDictionaryService{

	private static Logger logger = LoggerFactory.getLogger(DictionaryServiceImpl.class); 
	
	@Autowired
	private IDictionaryApi dictionaryApi;
	
	@Autowired
	private IRedisService redisService;
	
	@Override
	public ResultVo<ResDictionaryVo> update(DictionaryVo record, HttpServletRequest request) {

		ResultVo<ResDictionaryVo> resultVo = new ResultVo<>();
		resultVo.setCode(CodeConstant.SUCCESS);
		if(record.getDicList() != null && record.getDicList().size() > 0){
			List<DictionaryVo> list = record.getDicList();
			try {
				for (DictionaryVo dictionaryVo : list) {
					//有上班时间段设置，这里就不做设置了
//					if(CommonConstant.NON_WOKR_TIME.equals(dictionaryVo.getKeyword())){
//						String dicValue = dictionaryVo.getDicValue();
//						Pattern pattern = Pattern.compile("(\\d){2}(:)(\\d){2}(-)(\\d){2}(:)(\\d){2}");
//
//						Matcher matcher = pattern.matcher(dicValue);
//						if (! matcher.matches()){
//							resultVo.setCode(CodeConstant.REQ_PARAM_FAIL);
//							resultVo.setMsg("非工作日时间格式不正确，格式示例：18:00-06:00");
//							logger.error(LogUtil.msg("DictionaryServiceImpl:update", "非工作日时间格式不正确：" + dicValue));
//							continue;
//						}
//
//						String[] values = dicValue.split("-");
//						dictionaryVo.setDicValue(values[0]);
//						dictionaryVo.setDicField1(values[1]);
//						
//					}
//					
					dictionaryApi.update(dictionaryVo);
					initConf(request);
				}
			} catch (Exception e) {
				logger.error(LogUtil.msg("DictionaryServiceImpl:update", "修改数据异常：" + JSON.toJSONString(record)), e);
				resultVo.setCode(CodeConstant.EXCEPTION);
				resultVo.setMsg("修改数据异常");
				return resultVo;
			}
		}
		
		return resultVo;
	}
	
	@Override
	public ResultVo<?> initConf(HttpServletRequest request) {
		
		DictionaryVo vo = new DictionaryVo();
		vo.setStatus(1);
		List<ResDictionaryVo> list = dictionaryApi.list(vo);
		Map<String, String> map = new HashMap<>();
		ResultVo<?> resultVo = new ResultVo<>();
		if(list != null && list.size() > 0){
			for (ResDictionaryVo resDictionaryVo : list) {
				map.put(resDictionaryVo.getKeyword(), JSON.toJSONString(resDictionaryVo));
				if("AUTO_EXIT".equals(resDictionaryVo.getKeyword())){
					ConfConstant.sidCacheTime = Integer.parseInt(resDictionaryVo.getDicValue()) * 60;
				}
			}			
			try {
				redisService.delKey(CommonConstant.CACHE_SYS_CONF_KEY);
				redisService.setObject(CommonConstant.CACHE_SYS_CONF_KEY, map, 0);
				logger.info(LogUtil.msg("DictionaryServiceImpl:initConf", "将配置缓存到redis：" + JSON.toJSONString(list)));
			} catch (Exception e) {
				logger.error(LogUtil.msg("DictionaryServiceImpl:initConf", "初始化配置异常：" + JSON.toJSONString(list)), e);
				resultVo.setCode(CodeConstant.EXCEPTION);
				resultVo.setMsg("初始化配置异常");
				return resultVo;
			}	
		}
		
		
		resultVo.setCode(CodeConstant.SUCCESS);
		return resultVo;
	}

	@Override
	public ResultVo<ResDictionaryVo> getDicByKeyword(DictionaryVo vo, HttpServletRequest request) {
		
		String confStr = redisService.get(CommonConstant.CACHE_SYS_CONF_KEY);
		
		ResultVo<ResDictionaryVo> resultVo = new ResultVo<>();
		
		if (StrUtil.isNull(confStr)) {
			initConf(request);
			
			confStr = redisService.get(CommonConstant.CACHE_SYS_CONF_KEY);
			if (StrUtil.isNull(confStr)) {
				
				resultVo.setCode(CodeConstant.FAIL);
				logger.error(LogUtil.msg("DictionaryServiceImpl:getDicByKeyword", "获取配置失败：" + JSON.toJSONString(vo)));
				return resultVo;
			}
		}
		
		@SuppressWarnings("unchecked")
		Map<String, String> map = JSON.parseObject(confStr, HashMap.class);
		
		ResDictionaryVo resDictionaryVo =  JSON.parseObject(map.get(vo.getKeyword()), ResDictionaryVo.class);
		
		resultVo.setCode(CodeConstant.SUCCESS);
		resultVo.setData(resDictionaryVo);
		return resultVo;
	}
}
